package file_repo

import (
	"context"
	"errors"
	"fmt"
	"io"
	"os"
	"vmapp/app0/internal/biz/repo"
	"vmapp/app0/internal/conf"
	"vmapp/app0/internal/data/base"
	"vmapp/app0/internal/dto"
	"vmapp/app0/internal/models"

	"github.com/go-kratos/kratos/v2/log"
)

type fileRepo struct {
	*base.Data
	log  *log.Helper
}

func NewFileRepo(data *base.Data, component *conf.BootComponent) repo.FileRepo {
	return &fileRepo{
		Data: data,
		log:  component.Logger,
	}
}

func (t *fileRepo) CreateFile(ctx context.Context, one *models.File) error {
	return t.DB(ctx).Create(&one).Error
}

func (t *fileRepo) GetFileByHash(ctx context.Context, hash string) (one *models.File, err error) {
	err = t.DB(ctx).First(&one, "sha256 = ?", hash).Error
	return
}

func (t *fileRepo) GetFile(ctx context.Context, id int64) (one *models.File, err error) {
	err = t.DB(ctx).First(&one, "id = ?", id).Error
	return
}

func (t *fileRepo) DeleteFile(ctx context.Context, id int64) (err error) {
	err = t.DB(ctx).Delete(new(models.File), "id = ?", id).Error
	return
}

func (t *fileRepo) DeleteUploadFile(ctx context.Context, media int, vkey string) error {
	if media == 0 {
		return os.Remove("." + vkey)
	}
	return errors.New("介质不存在")
}

func (t *fileRepo) ListFile(ctx context.Context, req *dto.ListFileReq) (count int64, all []*models.File, err error) {
	if req.Current == 0 {
		req.Current = 1
	}

	if req.Size == 0 {
		req.Size = 10		
	}

	q := t.DB(ctx).Model(new(models.File))

	if req.Name != "" {
		q.Where(" name like ?", "%"+req.Name+"%")
	}

	if req.Type != 0 {
		q.Where("type = ?", req.Type)
	}

	err = q.Count(&count).Limit(req.Size).Offset((req.Current - 1) * req.Size).Order("id desc").Find(&all).Error
	return
}

func (t *fileRepo) UploadFile(ctx context.Context, vkey repo.Vkey, r io.Reader) (string, error) {
	key := fmt.Sprintf("%v%v/%v", vkey.LocalDir, vkey.Dir, vkey.FileName)

	// 保存
	if err := os.MkdirAll(fmt.Sprintf("./%v%v", vkey.LocalDir, vkey.Dir), 0755); err != nil {
		t.log.WithContext(ctx).Errorf("文件目录创建失败,%v", err)
		return "", err
	}
	out, err := os.OpenFile("."+key, os.O_WRONLY|os.O_CREATE, 0755)
	if err != nil {
		t.log.WithContext(ctx).Errorf("文件上传创建失败,%v", err)
		return "", err
	}
	defer out.Close()
	io.Copy(out, r)
	return key, nil
}
